class Solution(object):
    def nearestPalindromic(self, n):
        """
        :type n: str
        :rtype: str
        """
        k = len(n)
        int_n = int(n)
        if k == 0:
            int_n = int(n)
            return str(int_n - 1)
        if k % 2 == 0:
            l = k // 2
            base = int(n[:l])
            min_val = float('inf')
            for t1 in range(base - 1, base + 2):
                new_num = str(t1) + str(t1)[::-1]
                int_num = int(new_num)
                if int_num != int_n:
                    if min_val > abs(int_num - int_n):
                        min_val = abs(int_num - int_n)
                        r_num = int_num
                    else:
                        if min_val == abs(int_num - int_n):
                            r_num = min(r_num, int_num)
        else:
            l = k // 2
            base = int(n[:l])
            mid = int(n[l])
            min_val = float('inf')
            for t1 in range(base - 1, base + 2):
                for t2 in range(mid - 1, mid + 2):
                    if t1 > 0:
                        new_num = str(t1) + str(t2 % 10) + str(t1)[::-1]
                        int_num = int(new_num)
                        if int_num != int_n:
                            if min_val > abs(int_num - int_n):
                                min_val = abs(int_num - int_n)
                                r_num = int_num
                            else:
                                if min_val == abs(int_num - int_n):
                                    r_num = min(r_num, int_num)
        int_num = 10 ** k + 1
        new_num = str(int_num)
        if min_val > abs(int_num - int_n):
            min_val = abs(int_num - int_n)
            r_num = new_num
        else:
            if min_val == abs(int_num - int_n):
                r_num = min(r_num, int_num)
        int_num = 10 ** (k - 1) - 1
        new_num = str(int_num)
        if min_val > abs(int_num - int_n):
            min_val = abs(int_num - int_n)
            r_num = new_num
        else:
            if min_val == abs(int_num - int_n):
                r_num = min(r_num, int_num)
        return str(r_num)


data = Solution()
n = '99'
print(data.nearestPalindromic(n))

